package com.boil.qz.safekavass.shiro.filter;

import com.boil.qz.safekavass.model.LoginUser;
import com.boil.util.Constants;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.servlet.OncePerRequestFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * Created by ChenYong on 2017-04-14.
 * <br>
 * 菜单激活过滤器。
 */
public class MenuActiveFilter extends OncePerRequestFilter {
    /**
     * 日志
     */
    private static Logger log = LoggerFactory.getLogger(MenuActiveFilter.class);

    @Override
    protected void doFilterInternal(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        // 获取请求
        HttpServletRequest request1 = (HttpServletRequest) request;

        // 如果是 Get 请求
        if (Constants.REQUEST_GET.equals(request1.getMethod())) {
            // 获取登录用户的操作信息
            Subject subject = SecurityUtils.getSubject();

            // 已经登录
            if (subject.isAuthenticated()) {
                // 获取 Session，如果已经失效，则获取一个全新的
                Session session = subject.getSession();
                // 获取登录用户
                LoginUser loginUser = (LoginUser) session.getAttribute(Constants.LOGIN_USER);
                // 获取被激活的菜单 ID
                String menuId = request1.getParameter(Constants.MENU_ID);
                // 获取被激活的菜单父 ID
                String menuParentId = request1.getParameter(Constants.MENU_PARENT_ID);

                // 如果菜单 ID 和菜单父 ID 格式正确
                if (StringUtils.isNotBlank(menuId) && //
                        StringUtils.isNotBlank(menuParentId) && //
                        menuId.matches(Constants.NUMBER_RE) && // && //
                        menuParentId.matches(Constants.NUMBER_RE)) {
                    session.setAttribute(Constants.MENU_ID, Long.valueOf(menuId));
                    session.setAttribute(Constants.MENU_PARENT_ID, Long.valueOf(menuParentId));

                    log.debug("账号：{}，菜单 ID：{}，菜单父 ID：{}--->已存入 Session 中", //
                            loginUser.getLoginid(), //
                            menuId, //
                            menuParentId);
                }
            }
        }

        chain.doFilter(request, response);
    }
}